import dotenv from "dotenv";
dotenv.config();
import express from "express";
// todo: 导入其他必要的模块，如路由模块。
// 例如: import usersRouter from "./routes/users.js";
import usersRouter from "./routes/users.js";
import booksRouter from "./routes/books.js";
import categoriesRouter from "./routes/categories.js";
import db from "./db/connect-db.js";

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// todo: 设置路由
// 例如：app.use("/users", usersRouter);
app.use("/users", usersRouter);
app.use("/books", booksRouter);
app.use("/categories", categoriesRouter);

// 全局错误处理中间件
app.use((err, req, res, next) => {
  console.error("Path:", req.path, "Params:", req.params);
  console.error("Error Stack:", err.stack); // 输出完整堆栈
  res.status(500).json({ error: err.message || "服务器内部错误" });
});

app.listen(3000, () => {
  console.log("Server is running in localhost:3000");
});

//测试数据库连接
(async () => {
  try {
    await db.authenticate();
    console.log("✅ 数据库连接成功");
  } catch (error) {
    console.error("❌ 数据库连接失败:", {
      name: process.env.DATABASE_NAME,
      user: process.env.DATABASE_USERNAME,
      host: process.env.DATABASE_HOST,
      error: error.message,
    });
  }
})();
